/**
 * @name: 柱状图
 * @return {*}
 */

export const useBar = (api: Function, obj?: any, field?: string) => {
  let barOption: any = reactive({
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        rotate: 45
      }
    },
    grid: {
      x: '5%',
      right: '2%'
    },
    title: {
      left: 'center',
      top: '15',
      textStyle: {
        color: '#000',
        fontSize: 16
      }
    },
    yAxis: {
      type: 'value'
    },
    series: {
      label: {
        show: true,
        position: 'top',
        formatter: function (params: any) {
          return params.value.toLocaleString();
        }
      },

      data: [],
      type: 'bar'
    }
  });

  let loading = ref(true);
  const getData = (params: any) => {
    api(params)
      .then((data: any) => {
        barOption.xAxis.data = [];
        barOption.series.data = [];
        const f = (field || 'key,value').split(',');
        data.forEach((item: any) => {
          barOption.xAxis.data.push(item[f[0]]);
          barOption.series.data.push(item[f[1]]);
        });
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });
  };

  onBeforeMount(() => {
    if (obj?.params) {
      Object.keys(obj.params).forEach(key => {
        if (!barOption[key]) {
          barOption[key] = obj.params[key];
        } else {
          Object.assign(barOption[key], obj.params[key]);
        }
      });
    }
  });
  return {
    barOption,
    loading,
    getData
  };
};
